package com.kafka.kafka;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Kafka 生产者配置类
 */
@Configuration
@EnableKafka
public class KafkaProducerConfig {

    @Value("${kafka.servers}")
    private String servers;
    @Value("${kafka.max.message.size}")
    private int messagesize;
    @Value("${kafka.producer.topic}")
    private String topic;

    public String getTopic(){
        return topic;
    }

    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        //服务器地址
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        //1ms的批量发送时间间隔
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        //单条消息容量
        props.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG,messagesize);
        //KEY序列化
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        //VALUE序列化
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
        return props;
    }

    public ProducerFactory<String, byte[]> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public KafkaTemplate<String, byte[]> kafkaTemplate() {
        return new KafkaTemplate<String, byte[]>(producerFactory());
    }
}
